package com.sunrise.bean;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
import com.sunrise.boundary.UserManager;
import com.sunrise.entity.User;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import org.primefaces.event.SelectEvent;
import org.primefaces.event.UnselectEvent;

/**
 *
 * @author frank
 */
@Named(value = "userSearchBean")
@ManagedBean
@ViewScoped
public class UserSearchBean {

    @EJB
    UserManager um;

    public List<User> completeUserSearch(String query) {
        List<User> suggestions = um.findUserWithPublicCalSuggestions(query, um.getLoggedUser());
        return suggestions;
    }

    public void onUserSelect(SelectEvent event) {
        User u = (User)event.getObject();
        
        ExternalContext context = FacesContext.getCurrentInstance().getExternalContext(); 
        try {
            FacesContext.getCurrentInstance().getExternalContext().getFlash().put("searchedUser", u);
            context.redirect("publicCal.xhtml");
        } catch (IOException ex) {
            Logger.getLogger(UserSearchBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    // GUEST INVITATION
    List<User> invitees;

    public List<User> getInvitees() {
        if (invitees == null) {
            invitees = new ArrayList<>();
        }
        return invitees;
    }

    public void setInvitees(List<User> invitees) {
        this.invitees = invitees;
    }

    public void selectInviteeListener(SelectEvent event) {
        User u = (User)event.getObject();
        getInvitees().add(u);
    }

    public void unselectInviteeListener(UnselectEvent event) {
        User u = (User)event.getObject();
        getInvitees().remove(u);
    }

    public List<User> completeInvitee(String query) {
        List<User> suggestions = um.findUserSuggestions(query, um.getLoggedUser());
        List<User> myinvitees = getInvitees();
        if (myinvitees != null) {
            suggestions.removeAll(myinvitees);
        }
        return suggestions;
    }

    public void submit() {
//        System.out.println("hello");
    }
}
